package com.yyl.fmall.index.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yyl.fmall.index.entity.Category;
import com.yyl.fmall.index.mapper.CategoryMapper;
import com.yyl.fmall.index.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yyl.fmall.product.entity.Product;
import com.yyl.fmall.product.entity.ProductImg;
import com.yyl.fmall.product.service.IProductImgService;
import com.yyl.fmall.product.service.IProductService;
import com.yyl.fmall.utils.CommonConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品分类 服务实现类
 * </p>
 *
 * @author YuanSir
 * @since 2022-11-04
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {
    
    @Autowired
    private IProductService productService;
    
    @Autowired
    private IProductImgService productImgService;
    
    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public List<Category> getCategoryList() {
    
        List<Category> allCategoryList = list();
    
        return getFinalList(CommonConstants.CATEGORY_PARENT_ID,allCategoryList);
    }
    
    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public List<Category> getCategoryRecommends() {
    
        //1.查询顶级分类信息
        List<Category> fatherList = list(new LambdaQueryWrapper<Category>().eq(Category::getParentId, CommonConstants.CATEGORY_PARENT_ID));
        
        setProducts(fatherList);
        
        return fatherList;
    
    }
    
    private void setProducts(List<Category> fatherList) {
    
        //2.查询各顶级分类下的商品信息
        fatherList.forEach(category -> {
            
            //查询该分类下的商品按照销量排名的前6
            Page<Product> productPage = new Page<>(1,6);
            
            productService.page(productPage,new LambdaQueryWrapper<Product>()
                            .eq(Product::getRootCategoryId, category.getCategoryId())
                    .orderByDesc(Product::getSoldNum));
            
            
            //把查询到的商品信息挂载到category对象上
            List<Product> productList = productPage.getRecords();
            
            //判断如果当前顶级分类下真的有商品信息，在遍历填充图片
            if (productList != null && productList.size() > 0){
    
                //把商品的图片信息查出来
                Map<String, List<ProductImg>> productImgMap = productImgService
                        .list(new LambdaQueryWrapper<ProductImg>()
                                .in(ProductImg::getItemId, productList.stream()
                                        .map(Product::getProductId)
                                        .collect(Collectors.toList())))
                        .stream()
                        .collect(Collectors.groupingBy(ProductImg::getItemId));
    
                //处理商品对应的图片信息的填充
                productList.forEach(product -> {
    
                    List<ProductImg> productImgs = productImgMap.get(product.getProductId());
                    
                    if (productImgs == null){
                        
                        productImgs = new ArrayList<>();
                        
                    }
                    
                    product.setImgs(productImgs);
                
                });
            }
            
            category.setProducts(productList);
            
        });
    
    }
    
    private List<Category> getFinalList(Integer parentId ,List<Category> allCategoryList) {
        
        //1.查询出所有顶级分类信息，得到List<顶级分类>
        List<Category> fatherList = allCategoryList.stream()
                .filter(category -> category.getParentId().equals(parentId))
                .collect(Collectors.toList());
    
        Map<Integer, List<Category>> collect = allCategoryList.stream()
                .collect(Collectors.groupingBy(Category::getParentId));
    
        populateChildMenu(fatherList, collect);
        
        return fatherList;
    
    }
    
    private void populateChildMenu(List<Category> fatherList, Map<Integer, List<Category>> parentIdMap){
        
        fatherList.forEach(category -> {
    
            List<Category> categoryList = parentIdMap.get(category.getCategoryId());
            
            if (categoryList != null && categoryList.size() > 0){
                
                populateChildMenu(categoryList, parentIdMap);
    
                category.setCategories(categoryList);
                
            }
    
        });
        
    }
    
    private void populateChildMenu(List<Category> fatherList, List<Category> allCategoryList) {
    
        fatherList.forEach(category -> {
    
            // 查找当前菜单的下级菜单，返回childChildList
            List<Category> childList = findChildMenu(category, allCategoryList);
            
            if (childList.size() > 0){
    
                //为所有子菜单填充下级菜单
                populateChildMenu(childList, allCategoryList);
    
                //挂载子菜单到当前菜单
                category.setCategories(childList);
            }
        
        });
    
    }
    
    private List<Category> findChildMenu(Category category, List<Category> allCategoryList) {
    
        return allCategoryList.stream()
                .filter(category1 -> category.getCategoryId().equals(category1.getParentId()))
                .collect(Collectors.toList());
        
    }
}

